<template>
  <el-form :model="form" label-width="auto" style="max-width: 600px">
    <el-form-item label="用户账号">
      <el-input v-model="form.name" disabled/>
    </el-form-item>
    <el-form-item label="用户金额">
      <el-input v-model="form.money" disabled/>
    </el-form-item>

    <el-form-item label="会员计划">
      <el-select v-model="form.B_ID" placeholder="请选择用户计划">
        <view v-for="(data, index) in RankData" :key="index">
          <el-option :label="data.name" :value="data.ID" />
        </view>

      </el-select>
    </el-form-item>

<!--    <el-form-item label="用户状态">-->
<!--      <el-select v-model="form.status" placeholder="请选择用户状态">-->
<!--        <el-option label="启用" value="online" />-->
<!--        <el-option label="禁用" value="offline" />-->
<!--        <el-option label="隐藏" value="hide" />-->
<!--      </el-select>-->
<!--    </el-form-item>-->

    <el-form-item>
      <el-button type="primary" @click="onSubmit">确认提交</el-button>
      <el-button @click="emit('close-dialog')">取消</el-button>
    </el-form-item>

  </el-form>
</template>

<script lang="ts" setup>
import {reactive, onMounted, watch, ref} from 'vue'
import {ElLoading, ElMessage} from 'element-plus'
import {md5} from "js-md5";
import { defineProps } from 'vue';
import { defineEmits } from 'vue';
import router from "@/router";

const emit = defineEmits(['close-dialog'])

const props = defineProps({
  UID: String,
  name: String,
  money: String,
  cancel: Boolean,
});

const form = reactive({
  name: '',
  status: '',
  money: 0,
  B_ID:'2',
})

interface rank {
  ID: string,
  RID: string,
  name: string,
  type: string,
  price: string,
  time: string,
  status:string,
}

const RankData = ref<rank[]>([]);

const rank_editUrl = 'https://movie.cpb2013.top/admin/rank.php?mode=edit' // 替换为你的上传地址

const openFullScreen = () => {
  const loading = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(0, 0, 0, 0.7)',
  });
  return loading;
};

const closeFullScreen = (loading) => {
  loading.close();
};
// 表单提交处理函数
const onSubmit = async () => {
  console.log('提交表单:', form)
  let loading = openFullScreen();
  const formData = new FormData()

  // 遍历并添加到 FormData
  Object.keys(form).forEach((key) => {
    // 排除那些不是字符串或数字的键（例如布尔值或对象）
    // 因为 FormData 主要用于处理键值对形式的字符串数据
    if (typeof form[key] === 'string' || typeof form[key] === 'number') {
      formData.append(key, form[key]);
    } else if (typeof form[key] === 'boolean') {
      // 对于布尔值，你可以决定如何转换为字符串（例如，使用 'true' 或 'false'）
      formData.append(key, form[key] ? '女' : '男');
    }
  });
  formData.append('UID',props.UID);
  formData.append('func','admin');
  formData.delete('name');
  formData.delete('status');
  formData.delete('money')
  formData.append('key', localStorage.getItem('key'));
  try {
    const response = await fetch(rank_editUrl, {
      method: 'POST',
      headers: {
        // 'Authorization': `Bearer ${token}`,
        'Accept': 'application/json',
      },
      body: formData,
    })

    if (response.ok) {
      const result = await response.json()
      if(result['status'] ==='success')
      {
        ElMessage.success('修改成功！')
        emit('close-dialog')
        // this.$emit('close-dialog');
      }
      else if (result['status'] === 'danger') {
        localStorage.removeItem('key');
        ElMessage.error(result['msg']);
        await router.push('/login'); // Use router to navigate to the login page
      }
      else
      {
        ElMessage.error(result['msg'])
      }
    } else {
      ElMessage.error('添加失败！')
    }
  } catch (error) {
    ElMessage.error('请求失败！')
  }
  closeFullScreen(loading)
}

const fetchRankData = async () => {
  try {
    const formData = new FormData();
    formData.append('key', localStorage.getItem('key'));
    const response = await fetch('https://movie.cpb2013.top/admin/rank.php?mode=query', {
      method: 'POST',
      headers: {
        // 'Authorization': `Bearer ${token}`,
        'Accept': 'application/json',
      },
      body: formData,
    });
    const responseData = await response.json();
    if (responseData.status === 'success') {
      RankData.value = responseData.data.map((data: any) => ({
        ID: data.ID,
        RID: data.RID,
        name: data.name,
        type: data.type,
        price: data.price,
        time: data.time,
        status:data.status,
      }))
    }else if (responseData.status === 'danger') {
      localStorage.removeItem('key');
      ElMessage.error(responseData.msg);
      await router.push('/login'); // Use router to navigate to the login page
    } else {
      console.error('Error fetching movie data:', responseData.message);
    }
  } catch (error) {
    console.error('Error fetching movie data:', error);
  }
}

onMounted(() => {
  // const MID = '06a718d656fac9f771507e1872adc838'; // replace with actual MID
  form.name=props.name;
  form.money=props.money;
  fetchRankData()
});

watch(() => props.UID, (newUID) => {
  form.name=props.name;
  form.money=props.money;
  fetchRankData();
});

</script>
